#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
火之夜工作室 Flutter 项目创建脚本

基于当前项目模板创建一个新的 Flutter 项目
使用方法: 
1. 直接运行: python3 create_project.py
2. 使用参数文件: python3 create_project.py --params-file <参数文件路径>

参数文件格式:
project_type=app
template_type=1
project_name=hzy_example_project
package_name=com.example.hzy_example_project
display_name=Hzy Example Project
output_dir=/path/to/output
"""

import os
import sys
import argparse
import subprocess
from lib_copier import copy_lib_directory
from flutter_project_creator import run_flutter_create
import user_interaction
from utils import print_colored, update_readme


def read_params_file(file_path):
    """
    从参数文件中读取配置
    """
    params = {}
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            for line in f:
                line = line.strip()
                if line and '=' in line:
                    key, value = line.split('=', 1)
                    params[key.strip()] = value.strip()
        print_colored(f"已从参数文件加载配置: {file_path}", "green")
        return params
    except Exception as e:
        print_colored(f"读取参数文件失败: {str(e)}", "red")
        return {}


def main():
    """
    主函数
    """
    # 解析命令行参数
    parser = argparse.ArgumentParser(description='火之夜工作室 Flutter 项目创建工具')
    parser.add_argument('--params-file', help='参数文件路径')
    args = parser.parse_args()
    
    print_colored("\n火之夜工作室 Flutter 项目创建工具\n", "cyan")
    print_colored("该脚本将基于当前项目模板创建一个新的Flutter项目\n", "cyan")
    
    # 初始化参数
    params = {}
    project_type = None
    template_type = None
    project_name = None
    package_name = None
    display_name = None
    parent_dir = None
    target_dir = None
    
    # 从参数文件读取配置
    if args.params_file:
        params = read_params_file(args.params_file)
        if params:
            project_type = params.get('project_type')
            template_type = params.get('template_type')
            project_name = params.get('project_name')
            package_name = params.get('package_name')
            display_name = params.get('display_name')
            parent_dir = params.get('output_dir')
            if project_name and parent_dir:
                target_dir = os.path.join(parent_dir, project_name)
    
    # 获取项目类型，如果参数文件中没有提供，则交互式获取
    if not project_type:
        project_type = user_interaction.get_project_type()
    else:
        print_colored(f"使用参数文件中的项目类型: {project_type}", "blue")
    
    # 获取模板类型，如果参数文件中没有提供，则交互式获取
    if not template_type:
        template_type = user_interaction.get_template_type()
    else:
        print_colored(f"使用参数文件中的模板类型: {template_type}", "blue")
    
    # 获取当前脚本所在目录作为源目录
    source_dir = os.path.dirname(os.path.abspath(__file__))
    
    # 获取项目信息，如果参数文件中没有提供，则交互式获取
    if not all([project_name, package_name, display_name, parent_dir]):
        project_name, package_name, display_name, parent_dir, target_dir = user_interaction.get_project_info(source_dir, project_type)
    else:
        print_colored(f"使用参数文件中的项目信息:", "blue")
        print_colored(f"- 项目名称: {project_name}", "blue")
        print_colored(f"- 包名: {package_name}", "blue")
        print_colored(f"- 显示名称: {display_name}", "blue")
        print_colored(f"- 输出目录: {parent_dir}", "blue")
    
    # 验证目标目录是否存在并具有写权限
    if not os.path.exists(parent_dir):
        try:
            os.makedirs(parent_dir)
        except OSError as e:
            print_colored(f"错误: 无法创建目录 {parent_dir}: {str(e)}", "red")
            return 1
    
    # 检查目标目录是否具有写权限
    if not os.access(parent_dir, os.W_OK):
        print_colored(f"错误: 目录 {parent_dir} 没有写权限", "red")
        return 1

    # 检查目标目录是否已存在
    if os.path.exists(target_dir):
        # 如果参数文件中指定了覆盖选项，则直接使用
        if params.get('overwrite', '').lower() == 'y':
            print_colored(f"将覆盖目标目录: {target_dir}", "yellow")
        elif not user_interaction.confirm_overwrite(target_dir):
            print_colored("操作已取消", "yellow")
            return 1
    
    import shutil
    if os.path.exists(target_dir):
        shutil.rmtree(target_dir)
    
    # 获取Flutter路径参数
    flutter_path = params.get('flutter_path')
    if flutter_path:
        if os.path.exists(flutter_path) and os.access(flutter_path, os.X_OK):
            print_colored(f"使用提供的Flutter路径: {flutter_path}", "blue")
        else:
            print_colored(f"警告: 提供的Flutter路径无效或没有执行权限: {flutter_path}", "yellow")
            flutter_path = None
            
    # 如果没有提供有效的Flutter路径，尝试交互式获取
    if not flutter_path:
        # 尝试自动检测Flutter路径
        try:
            import platform
            system = platform.system()
            if system == 'Darwin' or system == 'Linux':  # macOS或Linux
                which_result = subprocess.run(['which', 'flutter'], 
                                            capture_output=True, 
                                            text=True)
                if which_result.returncode == 0:
                    flutter_path = which_result.stdout.strip()
                    print_colored(f"自动检测到Flutter路径: {flutter_path}", "blue")
            elif system == 'Windows':
                where_result = subprocess.run(['where', 'flutter'], 
                                            capture_output=True, 
                                            text=True, 
                                            shell=True)
                if where_result.returncode == 0:
                    flutter_path = where_result.stdout.strip().split('\n')[0]
                    print_colored(f"自动检测到Flutter路径: {flutter_path}", "blue")
        except Exception as e:
            print_colored(f"自动检测Flutter路径时出错: {str(e)}", "yellow")
            
        # 如果自动检测失败，尝试一些常见位置
        if not flutter_path:
            common_paths = [
                os.path.expanduser("~/flutter/bin/flutter"),
                os.path.expanduser("~/Documents/flutter/bin/flutter"),
                "/usr/local/bin/flutter",
                "/opt/flutter/bin/flutter"
            ]
            for path in common_paths:
                if os.path.exists(path) and os.access(path, os.X_OK):
                    flutter_path = path
                    print_colored(f"在常见位置找到Flutter: {flutter_path}", "blue")
                    break
    
    # 使用flutter create创建新项目
    if not run_flutter_create(target_dir, project_name, package_name, project_type, flutter_path):
        return 1
    
    # 复制项目文件
    template_branch = 'master' if template_type == '1' else 'depend-get'
    if not copy_lib_directory(source_dir, target_dir, project_name, project_type, package_name, display_name, branch=template_branch):
        return 1
    
    # 更新README.md
    update_readme(target_dir, project_name, display_name)

    # 打印完成信息
    print_colored(f"\n新项目已创建成功！", "green")
    print_colored(f"项目路径: {target_dir}", "green")
    print_colored(f"\n执行以下命令开始开发:\n", "blue")
    print_colored(f"cd {target_dir}", "yellow")
    print_colored(f"flutter pub get", "yellow")
    print_colored(f"flutter run", "yellow")
    
    # 获取用户选择的IDE类型，如果参数文件中没有提供，则交互式获取
    ide_choice = params.get('ide_choice')
    if not ide_choice:
        ide_choice = user_interaction.get_ide_choice()
    else:
        print_colored(f"使用参数文件中的IDE选择: {ide_choice}", "blue")
    
    # 自动打开项目
    from utils import open_project_in_ide
    open_project_in_ide(target_dir, ide_choice)
    
    return 0


if __name__ == "__main__":
    try:
        sys.exit(main())
    except KeyboardInterrupt:
        print_colored("\n操作已取消", "yellow")
        sys.exit(1)
    except Exception as e:
        print_colored(f"\n错误: {str(e)}", "red")
        sys.exit(1)